package com.air.common.controller.imp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.air.common.controller.IBaseController;
import com.air.common.util.BasicAppConstant;
import com.air.common.util.BasicErrorCode;
import com.air.common.util.WebUtil;
import com.air.common.vo.ResponseVO;
import com.air.common.vo.SubmitTokenVO;

@Controller
public abstract class BaseControllerImp implements IBaseController {
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	
	
	
	
	@Override
	@ExceptionHandler(Exception.class)
	public ModelAndView handleException(Exception ex, HttpServletRequest request,HttpServletResponse response) {
		logger.error("ERROR OCCURE!!! "+ex.getMessage());
		ex.printStackTrace();
		
		
		ResponseVO responseVO = new ResponseVO();
		responseVO.setException(ex);
		responseVO.setExecuteResult(false);
		responseVO.setErrCode(BasicErrorCode._ERRCODE_UNKNOWN);
		responseVO.setViewName(BasicAppConstant._VIEW_COMMON_ERROR);
		
		
		return parse2Mav(request,responseVO);
		
	}
	
	protected static ModelAndView parse2Mav(HttpServletRequest request,ResponseVO responseVO){
		ModelAndView mav = new ModelAndView();
		
		boolean isAnsyCalling = WebUtil.isAnsyCalling(request);
		if (isAnsyCalling){
			mav.setViewName(BasicAppConstant._VIEW_COMMON_JSON);
		}else{
			mav.setViewName(responseVO.getViewName());
		}
		
		if(request.getAttribute(BasicAppConstant._KEY_SUBMIT_TOKEN)!=null){
			SubmitTokenVO  submitToken = (SubmitTokenVO) request.getAttribute(BasicAppConstant._KEY_SUBMIT_TOKEN);
			responseVO.addObject(BasicAppConstant._KEY_SUBMIT_TOKEN, submitToken);
		}
		
		mav.addObject(BasicAppConstant._KEY_RESPONSE_VO, responseVO.toJsonFormat());
		
		return mav;
	}
	
}
